package com.gxa.jjty.phy.interceptor;

import com.gxa.jjty.core.common.ExceptionCode;
import com.gxa.jjty.core.exception.BusinessException;
import com.gxa.jjty.phy.service.impl.PhyUserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器(做权限校验)
 *
 * @ClassName PermissionInterceptor
 * @Author: ws
 * @date 2021/12/6 16:40
 */
@Component
public class PermissionInterceptor implements HandlerInterceptor {

    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    /**
     * 在方法拦执行前拦截，做的操作
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        // 把拦截时的操作定义在这里
        System.out.println("PermissionInterceptor preHandle");

        // 获取前端请求中的header，得到token
        String token = request.getHeader("token");

        // 判断redis中存储的token是否存在
        Object redisToken = redisTemplate.opsForValue().get(PhyUserServiceImpl.SECREAT + token);
//        System.out.println(PhyUserServiceImpl.SECREAT + token);
//        System.out.println(redisToken);

//        if (redisToken != null) {
//            // 存在即放行
//            return true;
//        }
//
//        // 抛出没有权限的异常
//        throw new BusinessException(ExceptionCode.NOT_LOGIN);
//
//        return false;

        return true;
    }

    /**
     * 方法执行后，放行了，再执行的操作
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           @Nullable ModelAndView modelAndView) throws Exception {
    }

    /**
     * 给jsp渲染时, 生成了数据模型Model后执行的操作
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                @Nullable Exception ex) throws Exception {
    }

}
